package com.mobis.friend.inteceptor;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import utils.JwtUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class JwtInteceptor implements HandlerInterceptor{
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        System.out.println("经过了拦截器");

        String authHeader=request.getHeader("Authorization");

        if(authHeader!=null&&authHeader.startsWith("Bearer ")){

            String token=authHeader.substring(7);

            Claims claims=jwtUtils.parseJWT(token);

            if (claims!=null){
                if ("admin".equals(claims.get("roles"))){
                    request.setAttribute("admin_claims",claims);
                }
                if ("user".equals(claims.get("roles"))){
                    request.setAttribute("user_claims",claims);
                }
            }

            request.setAttribute("","");


        }


        return true;
    }

}
